package com.gitee.feizns.quickstart.spring.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.function.Function;

/**
 * 代理
 * @author feizns
 * @since 2025/4/28
 */
public class Proxy {

    /**
     * 获取代理
     * @param proxyInterface 代理接口
     * @return {@link T }
     */

    public static <T> T getProxy(T target, Class<T> proxyInterface, Function<MethodInvocation, Object> methodProxy) {
        //noinspection NullableProblems
        return (T) ProxyFactory.getProxy(proxyInterface, new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) {
                return methodProxy.apply(new MethodInvocation() {
                    @Override
                    public Method getMethod() {
                        return invocation.getMethod();
                    }

                    @Override
                    public Object[] getArguments() {
                        return invocation.getArguments();
                    }

                    @Override
                    public Object proceed() throws Throwable {
                        return invocation.getMethod().invoke(target, invocation.getArguments());
                    }

                    @Override
                    public Object getThis() {
                        return invocation.getThis();
                    }

                    @Override
                    public AccessibleObject getStaticPart() {
                        return invocation.getStaticPart();
                    }
                });
            }
        });
    }

//    /**
//     * 获取代理
//     * @param proxyInterface 代理接口
//     * @return {@link T }
//     */
//
//    public static <T> T getProxy(T source) {
//        return (T) ProxyFactory.getProxy(new SingletonTargetSource(source));
//    }

}
